#define _GNU_SOURCE
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

static void
handler(int sig)
{
}

#define TESTSIG SIGUSR1

int main(int argc, char *argv[])
{
    if (argc != 2 || strcmp(argv[1], "--help") == 0){
        printf("%s num-sigs\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int numSigs = atoi(argv[1]);
    printf("Signal coutn %d\n", numSigs);
    struct sigaction sa;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sa.sa_handler = handler;
    if (sigaction(TESTSIG, &sa, NULL) == -1){
        puts("sigaction");
        exit(EXIT_FAILURE);
    }


    sigset_t blockedMask, emptyMask;
    sigemptyset(&blockedMask);
    sigaddset(&blockedMask, TESTSIG);
    if (sigprocmask(SIG_SETMASK, &blockedMask, NULL) == -1){
        puts("sigprocmask");
        exit(EXIT_FAILURE);
    }

    sigemptyset(&emptyMask);

    pid_t childPid = fork();
    switch (childPid) {
    case -1: puts("fork");
            exit(EXIT_FAILURE);

    case 0:     /* child */
        for (int scnt = 0; scnt < numSigs; scnt++) {
            if (kill(getppid(), TESTSIG) == -1){
                puts("kill");
                exit(EXIT_FAILURE);
            }
            if (sigsuspend(&emptyMask) == -1 && errno != EINTR){
                puts("sigsuspend");
                exit(EXIT_FAILURE);
            }
        }
        exit(EXIT_SUCCESS);

    default: /* parent */
        for (int scnt = 0; scnt < numSigs; scnt++) {
            if (sigsuspend(&emptyMask) == -1 && errno != EINTR){
                    puts("sigsuspend");
                    exit(EXIT_FAILURE);
            }
            if (kill(childPid, TESTSIG) == -1){
                puts("kill");
                exit(EXIT_FAILURE);
            }
        }
        exit(EXIT_SUCCESS);
    }
}